//
//  ADViewModel.m
//  ADKit
//
//  Created by 杜 泽旭 on 2017/12/2.
//  Copyright © 2017年 duzexu. All rights reserved.
//

#import "ADViewModel.h"
#import "ADKitHeaders.h"

NSString *const ADViewModelIDKey = @"ADViewModelIDKey";
NSString *const ADViewModelTitleKey = @"ADViewModelTitleKey";
NSString *const ADViewModelUtilKey = @"ADViewModelUtilKey";
NSString *const ADViewModelRequestKey = @"ADViewModelRequestKey";

@interface ADViewModel ()

@property (nonatomic, readwrite, weak) id<ADViewModelServices> services;
@property (nonatomic, readwrite, copy) NSDictionary *params;
@property (nonatomic, readwrite, strong) RACSubject *errors;

@end

@implementation ADViewModel
@synthesize storyboard = _storyboard,viewControllerClass = _viewControllerClass;

/// when `BaseViewModel` created and call `initWithParams` method , so we can ` initialize `
//+ (instancetype)allocWithZone:(struct _NSZone *)zone {
//    ADViewModel *viewModel = [super allocWithZone:zone];
//    @weakify(viewModel)
//    [[viewModel
//      rac_signalForSelector:@selector(initWithParams:)]
//     subscribeNext:^(id x) {
//         @strongify(viewModel)
//         [viewModel initialize];
//     }];
//    return viewModel;
//}

/// create `viewModel` instance
- (instancetype)initWithParams:(NSDictionary *)params {
    self = [super init];
    if (self) {
        /// 默认在viewDidLoad里面加载本地和服务器的数据
        self.shouldFetchLocalDataOnViewModelInitialize = YES;
        self.shouldRequestRemoteDataOnViewDidLoad = YES;
        /// 允许IQKeyboardMananger接管键盘弹出事件
        self.keyboardEnable = YES;
        self.shouldResignOnTouchOutside = YES;
        self.keyboardDistanceFromTextField = 10.0f;
        self.preferredStatusBarStyle = UIStatusBarStyleDefault;
        
        self.title = params[ADViewModelTitleKey];
        self.services = [ADKit services];
        self.params   = [params copy];
        self.viewControllerClass = [ADViewController class];
        
        @weakify(self);
        _popCommond = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            if (self.isPresented) {
                [self.services dismissViewModelAnimated:YES completion:nil];
            }else{
                [self.services popViewModelAnimated:YES];
            }
            return [RACSignal empty];
        }];
        
        /// system life cycle
        [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationWillResignActiveNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
            @strongify(self);
            [self applicationWillResignActive:x.object];
        }];
        [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
            @strongify(self);
            [self applicationDidEnterBackground:x.object];
        }];
        [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationWillEnterForegroundNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
            @strongify(self);
            [self applicationWillEnterForeground:x.object];
        }];
        [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidBecomeActiveNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
            @strongify(self);
            [self applicationDidBecomeActive:x.object];
        }];
        [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationWillTerminateNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
            @strongify(self);
            [self applicationWillTerminate:x.object];
        }];
        [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
            @strongify(self);
            [self applicationDidReceiveMemoryWarning:x.object];
        }];
        [self.services.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            @strongify(self);
            [self reachabilityStatusDidChange:status];
        }];
    }
    [self initialize];
    return self;
}

- (instancetype)init {
    return [self initWithParams:nil];
}

- (RACSubject *)errors {
    if (!_errors) _errors = [RACSubject subject];
    return _errors;
}

- (void)dealloc {
    ADLog(@"viewModel [%@] dealloc",self.class);
}

/// sub class can override
- (void)initialize {}

- (void)leftNavigationBarButtonItemAction:(UIBarButtonItem *)buttonItem {
    [self.popCommond execute:nil];
}

- (void)rightNavigationBarButtonItemAction:(UIBarButtonItem *)buttonItem {}

+ (NSString *)viewModelCachePath {
    NSString *dir = [NSFileManager.ad_cachesPath stringByAppendingPathComponent:@"dataCache"];
    if (![NSFileManager ad_isDirectoryExist:dir]) {
        [NSFileManager ad_createDirectoryAtPath:dir];
    }
    return dir;
}

- (NSString *)cachePath {
    return [ADViewModel.viewModelCachePath stringByAppendingPathComponent:NSStringFromClass(self.class)];
}

- (void)setPreferredStatusBarStyle:(UIStatusBarStyle)preferredStatusBarStyle {
    _preferredStatusBarStyle = preferredStatusBarStyle;
    [self.viewController setNeedsStatusBarAppearanceUpdate];
}

- (void)applicationWillResignActive:(UIApplication *)application {}

- (void)applicationDidEnterBackground:(UIApplication *)application {}

- (void)applicationWillEnterForeground:(UIApplication *)application {}

- (void)applicationDidBecomeActive:(UIApplication *)application {}

- (void)applicationWillTerminate:(UIApplication *)application {}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {}

- (void)viewDidLoad {}

- (void)viewWillAppear:(BOOL)animated {}

- (void)viewDidAppear:(BOOL)animated {}

- (void)viewWillDisappear:(BOOL)animated {}

- (void)viewDidDisappear:(BOOL)animated {}

- (void)reachabilityStatusDidChange:(AFNetworkReachabilityStatus)status {}

@end
